import { init } from 'snabbdom/build/package/init'
import { h } from 'snabbdom/build/package/h'

import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners'
import { styleModule } from 'snabbdom/build/package/modules/style.js'


const patch = init([
  eventListenersModule,
  styleModule
])
let sortBy = 'rank'
let vnode
let nextKey = 4
let totalHeight = 0
let margin = 8

// 列表数据

const originalData = [
  {rank: 1, title: 'Fight Club', desc: 'A story', elmHeight: 0},
  {rank: 2, title: 'Carol', desc: 'A love story', elmHeight: 0},
  {rank: 3, title: '12 Angry Men', desc: 'law story.', elmHeight: 0 }
]

let data = [...originalData]


// 创建列表项的vnode

function movieView (item) {
  return h('li.list-item', {
    key: item.rank,
    style: {
      opacity: '0',
      transform: 'translate(-200px)',
      delayed: { transform: `translateY(${item.offset}px)`, opacity: '1' },
      remove: { opacity: '0', transform: `translateY(${item.offset}px) translateX(200px)` }
    },
    hook: { insert: (vnode) => { item.elmHeight = vnode.elm.offsetHeight } }
  }, [
    h('div.rank', item.rank),
    h('div.title', item.title),
    h('div.desc', item.desc),
    h('div.btn.rm-btn', { on: { click: () => { remove(item) } } }, 'x')
  ])
}

// 创建列表的vnode

function view (data) {
  return h('div#container.cls', [
    h('h1', 'Top 3 movies'),
    h('div.btn-row', [
      h('div.btn-group', [
        h('a.btn', { on: { click: () => { changeSort('rank') } } }, 'rank'),
        h('a.btn', { on: { click: () => { changeSort('title') } } }, 'title'),
        h('a.btn', { on: { click: () => { changeSort('desc') } } },'desc')
      ]),
      h('a.btn.add', { on: { click: () => { add() } } }, 'Add')
    ]),
    h('ul.list',  { style: { height: totalHeight + 'px' } },  data.map(movieView))
  ])
}

// 排序

function changeSort (prop) {
  sortBy = prop
  data.sort((a, b) => {
    if (a[prop] > b[prop]) {
      return 1
    }
    if (a[prop] < b[prop]) {
      return -1
    }
    return 0
  })
 render()
}

// 新增数据项

function add () {
  var n = originalData[Math.floor(Math.random() * 3)]
  data = [{ rank: nextKey++, title: n.title, desc: n.desc, elmHeight: 0 }].concat(data)
  render()
  render()
}

// 移除数据项

function remove (item) {
  data = data.filter((m) => {
    return m !== item
  })
  render()
}




function render () {
  // 设置每一项的位置偏移量
  data = data.reduce((acc, m) => {
    var last = acc[acc.length - 1]
    console.log(last)
    m.offset = last ? last.offset + last.elmHeight + margin : margin
    return acc.concat(m)
  }, [])
  totalHeight = data.length === 0
    ? 0
    : data[data.length - 1].offset + data[data.length - 1].elmHeight
  vnode = patch(vnode, view(data))
}




// 初始HTML完全执行完

window.addEventListener('DOMContentLoaded', () => {
  let app = document.querySelector("#app")
  vnode = patch(app, view(data))
  render()
})
